﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using VisualWip.Core;
using VisualWip.Core.Interfaces;
using VisualWip.TFS2010Common;

namespace VisualWip.TFS2010Providers
{
    public abstract class WorkItemQueryBase : IQuery
    {
        private TfsConnection _connection;
        public TfsConnection Connection
        {
            get { return _connection; }
        }

        public Guid QueryId { get; set; }

        public bool DownloadDisplayFieldsOnly { get; set; }

        protected WorkItemQueryBase(TfsConnection connection)
        {
            _connection = connection;
        }
        #region IQuery Members

        public PersistenceTree Persist(string name)
        {
            var settings = new PersistenceTree(name, this);
            settings.AddChild(()=> Connection);
            settings.Add(() => QueryId);
            settings.Add(() => DownloadDisplayFieldsOnly);
            return settings;
        }

        public void Load(PersistenceTree settings)
        {
            _connection = settings.GetChild(() => Connection,new TfsConnection());
            QueryId = settings.Get(() => QueryId, Guid.Empty);
            DownloadDisplayFieldsOnly = settings.Get(() => DownloadDisplayFieldsOnly, false);
            Connection.Connect();
        }

        public string QueryText { get; set; }
        public IEnumerable<WorkItem> RunQuery()
        {
            RefreshQueryTextIfEmpty();
            try
            {
                return RunGetWork();
            }
            catch (Exception exception)
            {
                return new Collection<WorkItem>
                           {
                               new ErrorWorkItem(exception)
                           };
            }
        }

        public int RunCountQuery()
        {
            RefreshQueryTextIfEmpty();
            try
            {
                return RunGetWorkCount();
            }
            catch
            {
                return 0;
            }

        }

        public void Reset()
        {
            QueryText = string.Empty;
        }

        #endregion


        protected abstract Collection<WorkItem> RunGetWork();

        protected abstract int RunGetWorkCount();

        protected virtual void RefreshQueryTextIfEmpty()
        {
            if (string.IsNullOrWhiteSpace(QueryText))
                QueryText = Connection.WorkItemStore.GetQueryDefinition(QueryId).QueryText;
        }
    }
}